package com.jh.paymentchannel.service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.jh.paymentchannel.util.Util;
import com.jh.paymentchannel.util.ump.exception.VerifyException;
import com.jh.paymentchannel.util.ump.paygate.v40.Mer2Plat_v40;
import com.jh.paymentchannel.util.ump.paygate.v40.Plat2Mer_v40;

import cn.com.sandpay.cashier.sdk.util.CertUtil;
import cn.com.sandpay.cashier.sdk.util.CryptoUtil;
import net.sf.json.JSONObject;


@Controller
@EnableAutoConfiguration
public class QuickPayCallBackService {

	private static final Logger log = LoggerFactory.getLogger(QuickPayCallBackService.class);
	
	@Autowired
	Util util;
	
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/paymentchannel/topup/qp/notify_call")
	public @ResponseBody void notifycall(HttpServletRequest req, HttpServletResponse res) throws IOException{
				log.info("进入接口/v1.0/paymentchannel/topup/qp/notify_call================"+req.getParameterMap().toString());
				// 获取支付报文参数
				Map<String, String[]> params = req.getParameterMap();
				log.info("params================"+params);
				Map<String, String> map = new HashMap<String, String>();
				for (String key : params.keySet()) {
					String[] values = params.get(key);
					if (values.length > 0) {
						map.put(key, values[0]);
					}
				}
				log.info("map================"+map);
				JSONObject json = JSONObject.fromObject(map.get("data"));
				log.info("json================"+json.toString());
				if(null!=json||!"".equals(json)) {
					JSONObject head = JSONObject.fromObject(json.getString("head"));
					String respCode = head.getString("respCode");
					PrintWriter pw = res.getWriter();
					if(respCode.equals("000000")) {
						JSONObject jsonobj = JSONObject.fromObject(json.getString("body"));
						log.info("jsonobj================"+jsonobj.toString());
						String clearDate = jsonobj.getString("clearDate");
						String tradeNo = jsonobj.getString("tradeNo");
						String payTime = jsonobj.getString("payTime");
						String plMidFee = jsonobj.getString("plMidFee");
						String midFee = jsonobj.getString("midFee");
						String orderStatus = jsonobj.getString("orderStatus");
						String specialFee = jsonobj.getString("specialFee");
						String totalAmount = jsonobj.getString("totalAmount");
						String buyerPayAmount = jsonobj.getString("buyerPayAmount");
						String orderCode = jsonobj.getString("orderCode");
						String bid = jsonobj.getString("bid");
						String discAmount = jsonobj.getString("discAmount");
						String extraFee = jsonobj.getString("extraFee");
						/**更新订单状态*/
						/**调用下单，需要得到用户的订单信息*/
						RestTemplate restTemplate=new RestTemplate();
						
						URI uri = util.getServiceUrl("transactionclear", "error url request!");
						String url = uri.toString() + "/v1.0/transactionclear/payment/update";
						
						/**根据的用户手机号码查询用户的基本信息*/
						MultiValueMap<String, String> requestEntity  = new LinkedMultiValueMap<String, String>();
						requestEntity.add("status", "1");
						requestEntity.add("third_code",   tradeNo);
						requestEntity.add("order_code", orderCode  );
						String result = restTemplate.postForObject(url, requestEntity, String.class);
						
						/**判断是否有外放的通道的处理， 如果有那么继续回调外放哦*/
						uri = util.getServiceUrl("transactionclear", "error url request!");
						url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
						
						
						requestEntity  = new LinkedMultiValueMap<String, String>();
						requestEntity.add("order_code",  orderCode);
						result = restTemplate.postForObject(url, requestEntity, String.class);
						
						JSONObject jsonObject =  JSONObject.fromObject(result);
						JSONObject resultObj  =  jsonObject.getJSONObject("result");
						String outMerOrdercode  =  resultObj.getString("outMerOrdercode");
						String orderdesc        =  resultObj.getString("desc");
						String phone            =  resultObj.getString("phone");
						String  tranamount      =  resultObj.getString("amount");
						String channelTag       =  resultObj.getString("channelTag");
						String notifyURL        =  resultObj.getString("outNotifyUrl");
						if(outMerOrdercode != null && !outMerOrdercode.equalsIgnoreCase("")){
							uri = util.getServiceUrl("channel", "error url request!");
							url = uri.toString() + "/v1.0/channel/callback/yilian/notify_call";
							requestEntity  = new LinkedMultiValueMap<String, String>();
							requestEntity.add("merchant_no",  phone);
							requestEntity.add("amount",  tranamount);
							requestEntity.add("channel_tag",  channelTag);
							requestEntity.add("order_desc",  URLEncoder.encode(orderdesc, "UTF-8"));
							requestEntity.add("order_code",  outMerOrdercode);
							requestEntity.add("sys_order",   orderCode);
							requestEntity.add("notify_url", URLEncoder.encode(notifyURL, "UTF-8"));
							result = restTemplate.postForObject(url, requestEntity, String.class);
						}
						pw.write("success");
					}else {
						pw.write("fail");
					}
					pw.flush();
					pw.close();
				}

				
	       
	}
		
	@RequestMapping(method=RequestMethod.GET,value="/v1.0/paymentchannel/topup/qp/ret_url")
	public  String retcall(HttpServletRequest request, HttpServletResponse response) throws IOException{
		log.info("/v1.0/paymentchannel/topup/qp/ret_url=============== "+request.getParameterMap().toString());
		
		return "redirect:http://1.xinli2017.applinzi.com/login/zhufucg.html";
	}
	
	/*private  static String readContent(HttpServletRequest request) throws IOException{
		InputStream inputStream =null;
		ByteArrayOutputStream byteArray=null;
		try{
			inputStream= request.getInputStream();
			byteArray= new ByteArrayOutputStream();
			byte[] data = new byte[2048];
			int l = 0;
			while ((l = inputStream.read(data, 0, 2048)) != -1) {
				byteArray.write(data, 0, l);
			}
			byteArray.flush();
			return new String(byteArray.toByteArray(),"UTF-8");
		}finally{
			StreamKit.close(inputStream);
			StreamKit.close(byteArray);
		}
	}*/

	
}
